import React, { useState, useEffect } from 'react';
import { Container, Row, Col, Form, Button, Alert, Table, Tab, Tabs } from 'react-bootstrap';
import { useLocation, useNavigate } from 'react-router-dom';
import axios from 'axios';
import CourseCard from '../components/CourseCard';
import EditableTimeTable from '../components/EditableTimeTable';

const CourseList = () => {
  const location = useLocation();
  const navigate = useNavigate();
  const [courses, setCourses] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState('');
  const [fixedCourse, setFixedCourse] = useState(null);
  const [customSchedule, setCustomSchedule] = useState(null);
  const [filters, setFilters] = useState({
    专业: new URLSearchParams(location.search).get('专业') || '',
    年级: new URLSearchParams(location.search).get('年级') || '',
    排序方式: 'score', // score, easiness
    得分最低: '',
    得分最高: '',
    水课最低: '',
    水课最高: ''
  });

  useEffect(() => {
    if (!filters.专业 || !filters.年级) {
      navigate('/');
      return;
    }
    fetchCourses();
  }, [filters.专业, filters.年级]);

  const fetchCourses = async () => {
    try {
      setLoading(true);
      const response = await axios.get(`${process.env.REACT_APP_API_URL}/major-plans/majors/${filters.专业}/grade/${filters.年级}`);
      if (response.data.status === 'success') {
        setCourses(response.data.data);
      } else {
        setError('获取课程列表失败：' + response.data.message);
        console.error('获取课程列表失败:', response.data.message);
      }
    } catch (error) {
      setError('获取课程列表失败，请重试');
      console.error('获取课程列表失败:', error);
    } finally {
      setLoading(false);
    }
  };

  const handleFilterChange = (e) => {
    const { name, value } = e.target;
    setFilters(prev => ({
      ...prev,
      [name]: value
    }));
  };

  const handleFixCourse = (course) => {
    if (fixedCourse?.课程编号 === course.课程编号) {
      setFixedCourse(null);
    } else {
      setFixedCourse(course);
    }
  };

  const handleScheduleSave = (schedule) => {
    setCustomSchedule(schedule);
    console.log('保存课程表:', schedule);
  };

  const applyFilters = () => {
    fetchCourses();
  };

  const filterCourses = (courses, fixedCourse) => {
    if (!courses) return [];
    let filtered = [...courses];
    
    // 应用评分筛选
    if (filters.得分最低) {
      filtered = filtered.filter(course => course.平均评分 >= parseFloat(filters.得分最低));
    }
    if (filters.得分最高) {
      filtered = filtered.filter(course => course.平均评分 <= parseFloat(filters.得分最高));
    }
    
    // 应用水课程度筛选
    if (filters.水课最低) {
      filtered = filtered.filter(course => course.水课程度 >= parseFloat(filters.水课最低));
    }
    if (filters.水课最高) {
      filtered = filtered.filter(course => course.水课程度 <= parseFloat(filters.水课最高));
    }
    
    // 排序
    if (filters.排序方式 === 'score') {
      filtered.sort((a, b) => (b.平均评分 || 0) - (a.平均评分 || 0));
    } else if (filters.排序方式 === 'easiness') {
      filtered.sort((a, b) => (b.水课程度 || 0) - (a.水课程度 || 0));
    }
    
    // 过滤掉固定课程
    if (fixedCourse) {
      filtered = filtered.filter(course => {
        return course.课程编号 !== fixedCourse.课程编号 && 
               course.课程名称 !== fixedCourse.课程名称;
      });
    }
    
    return filtered;
  };

  if (loading) {
    return <div>加载中...</div>;
  }

  return (
    <Container fluid>
      <h2 className="mb-4">课程推荐</h2>
      {error && <Alert variant="danger">{error}</Alert>}

      <Tabs defaultActiveKey="list" className="mb-4">
        <Tab eventKey="list" title="课程列表">
          <Form className="mb-4">
            <Row>
              <Col md={4}>
                <Form.Group className="mb-3">
                  <Form.Label>排序方式</Form.Label>
                  <Form.Select
                    name="排序方式"
                    value={filters.排序方式}
                    onChange={handleFilterChange}
                  >
                    <option value="score">得分高低</option>
                    <option value="easiness">水课程度</option>
                  </Form.Select>
                </Form.Group>
              </Col>
            </Row>

            <Row>
              <Col md={6}>
                <Form.Group className="mb-3">
                  <Form.Label>得分高低范围（1-10分）</Form.Label>
                  <Row>
                    <Col>
                      <Form.Control
                        type="number"
                        name="得分最低"
                        value={filters.得分最低}
                        onChange={handleFilterChange}
                        placeholder="最低"
                        min="1"
                        max="10"
                      />
                    </Col>
                    <Col>
                      <Form.Control
                        type="number"
                        name="得分最高"
                        value={filters.得分最高}
                        onChange={handleFilterChange}
                        placeholder="最高"
                        min="1"
                        max="10"
                      />
                    </Col>
                  </Row>
                </Form.Group>
              </Col>

              <Col md={6}>
                <Form.Group className="mb-3">
                  <Form.Label>水课程度范围（1-10分）</Form.Label>
                  <Row>
                    <Col>
                      <Form.Control
                        type="number"
                        name="水课最低"
                        value={filters.水课最低}
                        onChange={handleFilterChange}
                        placeholder="最低"
                        min="1"
                        max="10"
                      />
                    </Col>
                    <Col>
                      <Form.Control
                        type="number"
                        name="水课最高"
                        value={filters.水课最高}
                        onChange={handleFilterChange}
                        placeholder="最高"
                        min="1"
                        max="10"
                      />
                    </Col>
                  </Row>
                </Form.Group>
              </Col>
            </Row>

            <Row>
              <Col>
                <div className="d-grid">
                  <Button onClick={applyFilters} variant="primary">
                    应用筛选
                  </Button>
                </div>
              </Col>
            </Row>
          </Form>

          {fixedCourse && (
            <div className="mb-4">
              <h4>已固定的课程</h4>
              <Table striped bordered hover>
                <thead>
                  <tr>
                    <th>课程名称</th>
                    <th>教师</th>
                    <th>学分</th>
                    <th>平均评分</th>
                    <th>水课程度</th>
                    <th>操作</th>
                  </tr>
                </thead>
                <tbody>
                  <tr>
                    <td>{fixedCourse.课程名称}</td>
                    <td>{fixedCourse.教师?.join(', ')}</td>
                    <td>{fixedCourse.学分}</td>
                    <td>{fixedCourse.平均评分?.toFixed(1) || 'N/A'}</td>
                    <td>{fixedCourse.水课程度?.toFixed(1) || 'N/A'}</td>
                    <td>
                      <Button
                        variant="danger"
                        size="sm"
                        onClick={() => handleFixCourse(fixedCourse)}
                      >
                        取消固定
                      </Button>
                    </td>
                  </tr>
                </tbody>
              </Table>
            </div>
          )}

          <h4 className="mb-3">推荐课程</h4>
          <Table striped bordered hover>
            <thead>
              <tr>
                <th>课程名称</th>
                <th>教师</th>
                <th>学分</th>
                <th>平均评分</th>
                <th>水课程度</th>
                <th>操作</th>
              </tr>
            </thead>
            <tbody>
              {filterCourses(courses, fixedCourse).map(course => (
                <tr key={course.课程编号}>
                  <td>{course.课程名称}</td>
                  <td>{course.教师?.join(', ')}</td>
                  <td>{course.学分}</td>
                  <td>{course.平均评分?.toFixed(1) || 'N/A'}</td>
                  <td>{course.水课程度?.toFixed(1) || 'N/A'}</td>
                  <td>
                    <Button
                      variant="primary"
                      size="sm"
                      className="me-2"
                      onClick={() => navigate(`/courses/${course.课程编号}`)}
                    >
                      详情
                    </Button>
                    <Button
                      variant="success"
                      size="sm"
                      onClick={() => handleFixCourse(course)}
                    >
                      固定
                    </Button>
                  </td>
                </tr>
              ))}
            </tbody>
          </Table>

          {courses.length === 0 && (
            <Alert variant="info">
              没有找到符合条件的课程
            </Alert>
          )}
        </Tab>

        <Tab eventKey="schedule" title="自定义课程表">
          <EditableTimeTable onSave={handleScheduleSave} />
        </Tab>
      </Tabs>
    </Container>
  );
};

export default CourseList; 